package cn.emall.sso.service.impl;


import cn.emall.jedis.JedisClient;
import cn.emall.mapper.TbUserMapper;
import cn.emall.pojo.TbUser;
import cn.emall.pojo.TbUserExample;
import cn.emall.sso.service.LoginService;
import cn.emall.utils.EmallResult;
import cn.emall.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;

/**
 * 用户登录处理
 */
@Service
public class LoginServiceImpl implements LoginService{

    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private JedisClient jedisClient;
    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @Override
    public EmallResult userLogin(String username, String password) {
        // 1、判断用户和密码是否正确
        //根据用户名查询用户信息
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        //执行查询
        List<TbUser> tbUsers = tbUserMapper.selectByExample(example);
        if(tbUsers == null || tbUsers.size() == 0){
            //返回登录失败
            return EmallResult.build(400,"用户名或密码错误");
        }
        //取用户信息
        TbUser tbUser = tbUsers.get(0);
        if(!DigestUtils.md5DigestAsHex(password.getBytes()).equals(tbUser.getPassword())){
            // 2、如果不正确，返回登录失败
            return EmallResult.build(400,"用户名或密码错误");
        }
        // 3、如果正确生成token。
        String token = UUID.randomUUID().toString();
        // 4、把用户信息写入redis，key：token value：用户信息
        tbUser.setPassword(null);
        jedisClient.set("SESSION:" + token, JsonUtils.objectToJson(tbUser));
        // 5、设置Session的过期时间
        jedisClient.expire("SESSION:" + token,SESSION_EXPIRE);
        // 6、把token返回
        return EmallResult.ok(token);
    }
}
